package com.suxin.netty;

import com.suxin.netty.server.MyChannelInboundHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;

import java.net.InetSocketAddress;

/**
 * @author Tang
 * @classname NettyServer
 * @description [  ]
 * @date 2021/7/17 9:08
 */
public class NettyServer {

    public static void main(String[] args) throws Exception {

        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workGroup = new NioEventLoopGroup(8);

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workGroup)
                .channel(NioServerSocketChannel.class)
                .childOption(ChannelOption.SO_KEEPALIVE, true)
                .childOption(ChannelOption.SO_BACKLOG, 1024)
                .childOption(ChannelOption.SO_RCVBUF, 1024)
                .childOption(ChannelOption.SO_SNDBUF, 1024);

        serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                System.out.println("收到客户端连接-->" + ch.hashCode());
                ch.pipeline()
//                        .addLast("MyChannelInboundHandler", new MyChannelInboundHandler());
//                        .addLast("StringDecoder", new StringDecoder())
//                        .addLast("StringEncoder", new StringEncoder())
//                        .addLast("ProtocolByteToMessageDecoder", new ProtocolByteToMessageDecoder())
//                        .addLast("ProtocolMessageToByteEncoder", new ProtocolMessageToByteEncoder())
                        .addLast("MyChannelInboundHandler", new MyChannelInboundHandler());
            }
        });

        ChannelFuture future = serverBootstrap
                .bind(new InetSocketAddress("127.0.0.1", 9999));
        future.addListener(new GenericFutureListener<Future<? super Void>>() {
            @Override
            public void operationComplete(Future<? super Void> future) throws Exception {
                if (future.isSuccess()) {
                    System.out.println("bind success!");
                }
            }
        }).sync().channel().closeFuture().sync();

        bossGroup.shutdownGracefully();
        workGroup.shutdownGracefully();
    }

}